import React,{useEffect,useState} from "react";
import { Text, View,StyleSheet,TouchableHighlight,Image,Modal,Pressable,ImageBackground,TouchableOpacity, SafeAreaView,Linking,ScrollView, Alert,Platform } from "react-native";
import * as S from "../Home/styles";
import { useFocusEffect, useRoute } from '@react-navigation/native';
import { Avatar, HStack, Center, NativeBaseProvider ,ChevronRightIcon,useToast} from "native-base";
import { useTheme } from 'styled-components';
import { /*RFValue*/ } from "react-native-responsive-fontsize";
import Icon from 'react-native-vector-icons/Ionicons';
import { useGlobal } from '../../utils/GlobalContext';
import { getUeser } from "../../services/user";
import { showToast } from "../../utils/toast";
import AsyncStorage from "@react-native-async-storage/async-storage";


const MadalScreen = ({modalVisible,setModalVisible}:any)=>{

  const [ pageNmu,setPageNum ] = useState(1)
  
  return(
    <Modal
      visible={modalVisible}
      transparent={false}
      animationType="fade"
      >
      <Pressable style={{flex:1,backgroundColor:'rgba(0, 0, 0, 0.72)',paddingTop:Platform.OS=='ios'? 0 :0}} onPress={()=>{
        setPageNum(pre=>pre+1)
        // Alert.alert(JSON.stringify(pageNmu))
        if(pageNmu>=1){
          setModalVisible(false)
          AsyncStorage.setItem('guideProfile','1')
        }
      }}>
        {/* <ImageBackground
          style={{flex:1,backgroundColor:'red'}}
          source={require("../../assets/guidePage/home_1.png")}
        ></ImageBackground> */}
        {
          pageNmu == 1 
          ?
          <Image
            style={{width:'100%',height:"100%",}}
            source={require("../../assets/guidePage/profile_1.png")}
          />
          :
          ''
        }



      </Pressable>
    </Modal>
    
  )
}





const UserModal = ({navigation}:any)=>{
  const { state, dispatch } = useGlobal();
  const [userInfo,setUserInfo] = useState({})

  const getUserInfo = ()=>{
    getUeser().then((res:any)=>{
      setUserInfo(res.data)
      dispatch({ type:'SET_USER' , payload:res.data })
    })
  }
  useEffect(() => {
    
    getUserInfo()


    return () => {

    };



  }, []);
  


  return (
    <TouchableOpacity onPress={() => {
      navigation.navigate("UserCenter",{getUserInfo})
    }}>
      <View style={styles.user}>
        {/* <Image style={styles.userAvatar} borderRadius={100} source={{ uri: userInfo.avatar }}/>
         */}
         <Avatar style={styles.userAvatar}  source={{
            uri: userInfo.avatar
            }}>
            <Image style={styles.userAvatar} source={require("../../assets/images/profile/avatar_default.png")} alt="" />
          </Avatar>
        <Text style={styles.userText}>{userInfo.nickName || '小T用户'}</Text>
      </View>
    </TouchableOpacity>
  )
}
const openBilibili = () => {
  Linking.openURL('https://www.bilibili.com');
};


const MenuList = ({navigation}:any)=>{

  const { state, dispatch } = useGlobal();
  

  const menuList = [
    { icon:require('../../assets/images/profile/icon_1.png'), name:"时间规划师", path:'Planner' },
    { icon:require('../../assets/images/profile/icon_3.png'), name:"遗愿清单", path:'LastWishList' },
    { icon:require('../../assets/images/profile/icon_2.png'), name:"时间币", path:'' },
    { icon:require('../../assets/images/profile/icon_5.png'), name:"问题反馈", path:'FeedBack' },
    // { icon:require('../../assets/images/profile/icon_6.png'), name:"视频介绍", path:'https://www.bilibili.com',isLink:true },
    { icon:require('../../assets/images/profile/icon_6.png'), name:"操作手册", path:'WebView',params:'https://n2xs4toi9s.feishu.cn/docx/OkXSdmixwoReKzx6Z82cN13MnLd?from=from_copylink'},
    { icon:require('../../assets/images/profile/icon_7.png'), name:"隐私协议", path:'WebView',params:'https://xiaot.club/doc/#/'},
  ]
  
  return(
    <ScrollView showsVerticalScrollIndicator={false} style={styles.pageList}>
      {menuList.map((item, index) => (
        <View key={index}>
          <MenuItme children={item} navigation={navigation} key={index}/>
        </View>
      ))}
      <Text style={styles.version}>版本号 V{state.primaryVersionCode}.{state.secondryVersionCode}.{state.tertiaryVersionCode}</Text>
    </ScrollView>
  )
   
}

const MenuItme = ({children,navigation}:any)=>{
  const toast = useToast();

  const theme = useTheme();

  const itemClick = (children:any,navigation:any)=>{

    // navigation.setOptions({
    //   tabBarStyle: {
    //     ...Platform.select({
    //        ios: {
    //            shadowOffset: {width: 0, height: 0},
    //        },
    //        android: {
    //            elevation: 0,
    //        },
    //     }),
    //     borderTopWidth: 0,
    //     height: (62),
    //     paddingBottom: 7,
    //     paddingHorizontal: /*RFValue*/(8),
    //     paddingTop: 7,
    //     backgroundColor: theme.colors['background-variant'],
    //   },
    // });
    // return
    if(children.path){
      if(children.params){
        navigation.navigate(children.path,{name:children.name,path:children.params})
        // openBilibili()
      }else{
        navigation.navigate(children.path)
      }
    }else{
      // toast.show({
      //   description: "开发中",
      //   // placement: "top"
      // })
      showToast("", "", "开发中");
    }
  }
  return (
    <View>
    <TouchableHighlight 
      underlayColor='#333'
      style={{marginTop:20,borderRadius:16}}
      onPress={() => {
        itemClick(children,navigation)
      }}>

      <View  style={styles.pageItem}>  
        <View style={styles.pageItemLeft}>
        <Image style={{marginRight:16,width:24,height:24}} borderRadius={0} source={children.icon} alt="" />
          <Text style={styles.pageItemText}>{children.name}</Text>
        </View>
        <View style={styles.pageItemRight}>
          <ChevronRightIcon color="rgba(209, 209, 214, 1)" />
        </View>
      </View>

    </TouchableHighlight>
    </View>
  )
}

const Title = ({navigation}:any)=>{
  const { state, dispatch } = useGlobal();

  useEffect(() => {
    // init()
    dispatch({ type:'SET_TOKEN' , payload:'d6ea4c4b24e21b7a5a625c138712183d' })
    return () => {

    };



  }, []);

  return <Text>{state.token}</Text>;
}


const Profile = ({navigation}:any) => {

  const [modalVisible, setModalVisible] = useState(false);
  const fetchData =  async ()=>{
    let guideProfile = await AsyncStorage.getItem('guideProfile')
    if(!guideProfile){
      setModalVisible(true)
    }
  }


  useEffect(() => {
    // AsyncStorage.removeItem('guideProfile')
    fetchData()
    return () => {

    };
  }, []);




  return (
    <ImageBackground
      source={require("../../assets/images/profile/plannerBg.jpg")}
      style={styles.background}
    >
    {/* <S.GrayContainer> */}
      {/* <Title/> */}
      <SafeAreaView style={{paddingTop:20,height:'100%'}}>
        <NativeBaseProvider>
          <View style={styles.container}>
            <UserModal navigation={navigation}/>
            <MenuList navigation={navigation}/>
            {/* <TouchableOpacity onPress={()=>{

              Linking.openURL('https://itunes.apple.com/app/com.xiaoT.xiaoT')
              .catch((err) => console.error('无法打开应用商店链接：', err));

            }}>
              <Text>123123</Text>
            </TouchableOpacity> */}
          </View>
        </NativeBaseProvider>
      </SafeAreaView>
      
    {/* </S.GrayContainer> */}
    <MadalScreen modalVisible={modalVisible} setModalVisible={setModalVisible}/>
    </ImageBackground>
   
  );
};

export default Profile;
const styles = StyleSheet.create({
  background:{
    flex: 1,
    resizeMode: 'cover', // 设置图片填充方式
    // justifyContent: 'center',
  },
  container:{
    height:"100%",
    width:'100%',
    alignItems:'center',
    paddingHorizontal:16,
  },
  user:{
    marginTop:22,
    alignItems:'center',
    marginBottom:24,
  },
  userAvatar:{
    borderColor:'#fff',
    borderWidth:2,
    width:86,
    height:86,
    borderRadius:100,
  },
  userText:{
    fontFamily: "HarmonyOS_Sans_SC_Bold",
    fontSize:24,
    color:'#000000',
    marginTop:12,
    fontWeight:'500'
  },
  pageList:{
    width:'100%'
  },
  pageItem:{
    width:"100%",
    backgroundColor:'#fff',
    // marginTop:20,
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center',
    paddingHorizontal:16,
    paddingVertical:14,
    borderRadius:16,
  },
  pageItemLeft:{
    flexDirection:'row',
    alignItems:'center'
  },
  pageItemText:{
    color:'#000',
    fontSize:16,
    fontWeight:'400',
    // fontFamily: "HarmonyOS_Sans_SC_Bold"
  },
  pageItemRight:{},
  version:{
    textAlign:'center',
    marginTop:32,
    fontSize:14,
    color:'rgba(209, 209, 214, 1)',
    fontFamily:'HarmonyOS Sans SC'
  }
})
